package com.huluobo.kotlinim1911a

import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.media.SoundPool
import android.os.Build
import androidx.annotation.RequiresApi
import cn.bmob.v3.Bmob
import com.huluobo.kotlinim1911a.adapter.EMMessageListenerAdapter
import com.huluobo.kotlinim1911a.ui.activity.ChatActivity
import com.huluobo.kotlinim1911a.ui.activity.MainActivity
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import com.hyphenate.chat.EMOptions
import com.hyphenate.chat.EMTextMessageBody

/**
 * Created by lc on 2022/6/23.
 */
class IMApplication : Application() {
    companion object {
        lateinit var instance: IMApplication
        //因为伴生函数类似于静态代码块,在类初始化时调用
        //也就是说会在onCreate之前调用,这样肯定会产生空指针
        //使用lateinit,则会在onCreate之后创建实例
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    val soundPool: SoundPool = SoundPool.Builder().setMaxStreams(10).build()

    val duan by lazy {
        soundPool.load(instance, R.raw.duan, 0)
    }

    val yulu by lazy {
        soundPool.load(instance, R.raw.yulu, 0)
    }

    private val messageListener = object : EMMessageListenerAdapter() {
        override fun onMessageReceived(messages: MutableList<EMMessage>?) {
            //判断当前应用在前台还是后台
            if (isForeground()) {
                soundPool.play(duan, 1f, 1f, 0, 0, 1f)
            } else {
                soundPool.play(yulu, 1f, 1f, 0, 0, 1f)
                //当前应用处于后台位置时,接收消息弹出通知
                showNotification(messages)
            }
        }
    }

    private fun showNotification(messages: MutableList<EMMessage>?) {
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        messages?.forEach {
            var contentText = "非文本消息"
            if (it.type == EMMessage.Type.TXT) {
                contentText = (it.body as EMTextMessageBody).message
            }//[图片][表情][视频]

            val intent = Intent(this, ChatActivity::class.java)
            intent.putExtra("username", it.conversationId())

            val taskStackBuilder =
                TaskStackBuilder.create(this).addParentStack(MainActivity::class.java)
                    .addParentStack(ChatActivity::class.java)
                    .addNextIntent(intent)//首先跳转到MainActivity(Parent),再跳转到ChatActivity

            val pendingIntent =
                taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)

            val notification = Notification.Builder(this)
                .setContentTitle(getString(R.string.receive_new_message))//通知的标题
                .setContentText(contentText)//通知的内容
                .setLargeIcon(
                    BitmapFactory.decodeResource(
                        resources, R.mipmap.avatar1
                    )//通知中的大图标
                )
                .setSmallIcon(R.mipmap.ic_contact)//状态栏上的小图标
                .setContentIntent(pendingIntent)//设置点击跳转的intent
                .setAutoCancel(true)//设置是否自动回弹
                .setFullScreenIntent(pendingIntent, true)//设置当有其他app处于全屏状态时,当前app通知的优先级
                .build()
            notificationManager.notify(1, notification)
        }
    }

    private fun isForeground(): Boolean {
        val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        for (runningAppProcess in activityManager.runningAppProcesses) {
            if (runningAppProcess.processName == packageName) {
                //找到当前运行的app的进程
                //判断当前app运行的关键级是否等于处于前台位置的关键级
                return runningAppProcess.importance ==
                        ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
            }
        }
        return false
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        val options = EMOptions();
        options.appKey = "moroks#kotlinim1911a"
        // 其他 EMOptions 配置。
        EMClient.getInstance().init(this, options)
        //在做打包混淆时,需要关闭掉debug模式,避免消耗不必要的资源
        EMClient.getInstance().setDebugMode(BuildConfig.DEBUG)

        //Bmob后端云初始化
        Bmob.initialize(this, "a497ffed60d17dde5033edc7fc90abaf")

        EMClient.getInstance().chatManager().addMessageListener(messageListener)
        soundPool.play(duan, 1f, 1f, 0, 0, 1f)
        soundPool.play(yulu, 1f, 1f, 0, 0, 1f)
    }
}